package com.onurokan.someone4me.role.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.onurokan.someone4me.role.domain.Authority;
import com.onurokan.someone4me.role.domain.AuthorityTypeEnum;
import com.onurokan.someone4me.user.domain.User;

@Repository
@Transactional
public class HibernateAuthorityDao implements AuthorityDao {

	private SessionFactory sessionFactory;

	@Autowired
	public HibernateAuthorityDao(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	public Authority loadAuthorityByEnumType(AuthorityTypeEnum type) {
		String role = type.toString();
		Criteria criteria = currentSession().createCriteria(Authority.class);
		criteria.add(Restrictions.eq("role", role));
		List list = criteria.list();
		if (list.isEmpty()) {
			return null;
		}
		return (Authority) list.get(0);
	}

	public void addAuthority(Authority authority) {
		currentSession().save(authority);
	}

}
